package org.kugua.effect.impl;

import java.awt.*;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.QuadCurve2D;

import lombok.extern.slf4j.Slf4j;
import org.kugua.context.CaptchaContext;
import org.kugua.effect.IEffect;
import org.kugua.enums.QuestionAnswerType;
import org.kugua.utils.RandomUtils;

/**
 * 贝塞尔曲线-干扰效果
 *
 * @author 苦瓜
 * @create 2024-08-27
 * @since 1.0.0
 */
@Slf4j
public class BesselLineEffect implements IEffect {

    /**
     * 贝塞尔曲线数量
     */
    private Integer num  = 10;

    private Float lineWidth = 2.0f;

    public void setLineWidth(Float lineWidth) {
        this.lineWidth = lineWidth;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    /**
     * 贝塞尔曲线-干扰效果
     *
     * @param context 上下文信息
     */
    @Override
    public void effect(CaptchaContext context) {
        log.trace("BesselLineEffect Effect Process.");
        if (QuestionAnswerType.IMAGE_ANSWER.getType().equals(context.getQuestionAnswerType())) {
            return;
        }
        int width = context.getWidth();
        int height = context.getHeight();
        Graphics2D graphics = context.getGraphics();
        log.trace("draw bessel Line. width: {}, height: {}", width, height);

        for (int i = 0; i < num; i++) {
            Color color = new Color(RandomUtils.random(255),
                    RandomUtils.random(255), RandomUtils.random(255));
            graphics.setColor(color);
            // 起始点(以height/2 为y轴分割线条，起始点为正)
            int startX = 10;
            int startY = 10 + RandomUtils.random(height / 2);
            // 终点(终点为负)
            int endX = width - 10;
            int endY = (height / 2) + RandomUtils.random(height - 10);
            // 贝塞尔曲线阶数，通过随机奇偶数进行判断
            int random = RandomUtils.random(2);
            // 二阶贝塞尔曲线
            if (random % 2 == 0) {
                // 控制点
                int contX = (width / 3) + RandomUtils.random(width / 3);
                int contY = 10 + RandomUtils.random(height - 10);
                QuadCurve2D shape = new QuadCurve2D.Double();
                shape.setCurve(startX, startY, contX, contY, endX, endY);
                graphics.setStroke(new BasicStroke(lineWidth));
                graphics.draw(shape);
                continue;
            }
            // 三阶贝塞尔曲线
            int contX = (width / 4) + RandomUtils.random(width / 2);
            int contY = 10 + RandomUtils.random(height - 10);
            int contX1 = (width / 2) + RandomUtils.random(width / 4);
            int contY1 = 10 + RandomUtils.random(height - 10);
            CubicCurve2D shape = new CubicCurve2D.Double(startX, startY, contX, contY, contX1, contY1, endX
                    , endY);
            graphics.setStroke(new BasicStroke(lineWidth));
            graphics.draw(shape);
        }
        // 恢复原来的，避免影响其他效果
        graphics.setStroke(new BasicStroke());
    }
}
